<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use Session,DB;
/**
 * 系统通知消息
 */
class Message extends Model
{
    protected $table = 'message';
    public $timestamps = false;
    protected $guarded = [];
    
    // 获取用户的消息
    public static function getUserMessage()
    {
        // 获取用户id
        $user_id = Session::get('userData')->id;
        // 获取所有的消息，按照阅读状态还有消息id来排序
        $msgs = DB::table('message_read')->where('user_id', $user_id)
                ->where('flag', 1)
                ->orderBy('id', 'desc')
                ->orderBy('is_read', 'asc')
                ->paginate(20);
        
        // 循环所有消息，获取消息标题和内容
        foreach($msgs as $msg){
            $msg->msgInfo = self::where('id', $msg->msg_id)->first();
        }
        
        return $msgs;
    }
    
    // 用于自动发送消息给前台用户
    public function autoSendMessage($uid, $data)
    {
        $data['user_id'] = $uid;
        $data['msg_time'] = date('Y-m-d H:i:s');
        $data['msg_type'] = 1;
        $res = Message::insertGetId($data);
        if($res){
            $readData = ['user_id' => $uid,'msg_id' => $res];
            DB::table('message_read')->insert($readData);
        }
        return;
    }
}
